package com.campuscarbooking.api.repository;

import com.campuscarbooking.api.model.BusSchedule;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

@Repository
public interface BusScheduleRepository extends JpaRepository<BusSchedule, Long> {

    Page<BusSchedule> findByRouteDirectionAndIsFixedAndStatus(
            BusSchedule.RouteDirection routeDirection,
            Boolean isFixed,
            BusSchedule.Status status,
            Pageable pageable);

    @Query("SELECT bs FROM BusSchedule bs WHERE bs.routeDirection = ?1 AND bs.isFixed = ?2 " +
            "AND bs.departureTime >= ?3 AND bs.departureTime <= ?4 AND bs.status = 'active'")
    List<BusSchedule> findAvailableSchedules(
            BusSchedule.RouteDirection routeDirection,
            Boolean isFixed,
            LocalTime startTime,
            LocalTime endTime);

    @Query("SELECT COUNT(r) FROM Reservation r WHERE r.schedule.id = ?1 AND r.status <> 'canceled'")
    Integer countReservationsByScheduleId(Long scheduleId);
} 